<template>
  <div class="imgupload">
    <!-- 上传的组件 -->
    <el-upload
      action="#"
      v-if="!imgUrl"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <div class="box" v-else>
      <img
        @click="previewImg"
        v-errimg="defaultImg"
        class="img"
        :src="imgUrl"
      />
      <i @click="clearimg" class="el-icon-close"></i>
    </div>
    <el-dialog title="预览图片" :visible.sync="previewShow">
      <div class="prebox">
        <img class="preimg" :src="imgUrl" alt="" />
      </div>
    </el-dialog>
    <!-- 图片预览 -->
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'

export default {
  name: 'imgupload',
  props: ['imgUrl'],
  data () {
    return {
      previewShow: false,
      COS: null,
      defaultImg: require('@/assets/common/avatar.jpg')
    }
  },
  methods: {
    clearimg () {
      this.$emit('update:imgUrl', '')
    },
    previewImg () {
      this.previewShow = true
    },
    beforeUpload (file) {
      let limit2M = file.size / 1024 / 1024 < 2
      let imgType =
        file.type == 'image/jpeg' ||
        file.type == 'image/png' ||
        file.type == 'image/gif'
      if (!limit2M) {
        this.$message.error('图片大小不能超过2M请压缩图片画质')
      }
      if (!imgType) {
        this.$message.error('图片必须是jpg|png|gif')
      }
      return limit2M && imgType
    },
    httpRequest (file) {
      console.log(file)
      const myfile = file.file
      this.COS.putObject(
        {
          Bucket: 'hr73-1252192193' /* 必须 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: myfile.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: myfile, // 上传文件对象
          onProgress: progressData => {
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(data)
          // data:上传成功后的返回值
          // err:上传出错的错误信息
          // console.log('http://' + data.Location)
          // 将返回的图片地址赋值给 url
          this.$emit('update:imgUrl', 'http://' + data.Location)
        }
      )
    }
  },
  created () {
    // 初始化存储对象
    this.COS = new COS({
      SecretId: 'AKIDjLn7GGdNPl061lBpCOQH0dJxQiqmqdIl',
      SecretKey: 'iUDl8JKApOn1Y2LTQQfmiTBi6JLC2nOr'
    })
  }
}
</script>

<style lang="scss" scoped>
.imgupload {
  .box {
    width: 150px;
    height: 150px;
    position: relative;
    .img {
      width: 150px;
      height: 150px;
    }
    i {
      position: absolute;
      top: 0;
      right: 0;
      padding: 4px;
      background-color: #ccc;
      color: #fff;
      border-radius: 0 0 0 20px;
      cursor: pointer;
    }
  }
}
</style>
